import storage from './storage'
import { generateUrl, createOption, getRequest } from './request'
import config from '../config'
import { DeviceEventEmitter } from 'react-native'

// 获取token
export function getToken() {
  return storage.load({key: 'token'})
}

// 设置token
export function setToken(data) {
  storage.save({
    key: 'token',
    data: data
  }).then(() => {
    DeviceEventEmitter.emit('loginEvent')
  })
}

// 删除token
export function removeToken() {
  storage.remove({
    key: 'token'
  })
}

/**
*  检查token失效
*  return 0可用,1过期,2失效
*/
export function checkTokenExpire(token) {
  let currentTime = new Date().getTime();
  let expireTime = new Date(token.expire.replace(/-/g, '/')).getTime()
  let invalidTime = new Date(token.invalid.replace(/-/g, '/')).getTime()
  // 已失效
  if(currentTime > invalidTime) {
    removeToken()
    return 2
  }
  // 过期之前多少毫秒可刷新
  let refreshTime = config.token.refreshSecond * 1000
  // 已过期
  if( currentTime > (expireTime - refreshTime) ) {
    return 1
  }

  return 0
}

// 刷新token
export function refreshToken(token) {
  let option = {
    method: 'post',
    path: 'auth/token/refresh'
  }

  let url = generateUrl(option.path)
  url += '?token=' + token
  let requestOption = createOption(option, url).requestOption

  return new Promise(function(resolve, reject) {
    getRequest(requestOption, url).then(response => {
      setToken(response)
      resolve(response.token)
    })
  })
}
